
#include <stdint.h>
#include "systick.h"
#include "os.h"
#include "stm32f10x.h"

static void delay_us_impl(uint32_t us) {
    uint32_t periodic_systick = SysTick->LOAD + 1;
    uint32_t start_systick = SysTick->VAL;
    uint64_t start_os_ticks = get_os_ticks();
    uint32_t except_ticks_duration = us * (SystemCoreClock/8000000);
    
    while(1) {
        if((get_os_ticks() - start_os_ticks) * periodic_systick + (start_systick - SysTick->VAL) >= except_ticks_duration)
            break;
    }
}

void delay_us(uint32_t us) {
    if(!us) return;

    OS_ERR err;
    OSSchedLock(&err);
    delay_us_impl(us);
    OSSchedUnlock(&err);
}

void delay_ms(uint32_t ms) {
    if(!ms) return;

    OS_ERR err;
    OSSchedLock(&err);
    delay_us_impl(ms * 1000);
    OSSchedUnlock(&err);
}
